using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-出库商品详细服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpOutstockProductService : IApplicationService 
{
    private readonly SugarRepository<ErpOutstockProduct> _thisRepository;
    public ErpOutstockProductService(SugarRepository<ErpOutstockProduct> thisRepository)
    {
        _thisRepository = thisRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<ErpProductReturnDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .Where(m=>m.OutStockId==param.Id)
            .OrderByDescending(m=>m.Id)
            .ToListAsync();
        var productIds = query.Select(m => m.ProductId).ToList();
        var productRepository = _thisRepository.ChangeRepository<SugarRepository<ErpProduct>>();
        var productQuery = await productRepository.AsQueryable()
            .Where(m=>productIds.Contains(m.Id))
            .Includes(m=>m.Type)
            .Includes(m=>m.Unit)
            .Includes(m=>m.Supplier)
            .OrderByDescending(m=>m.Id)
            .ToListAsync();
        var result= productQuery.Adapt<List<ErpProductReturnDto>>();
        foreach (var item in result)
        {
            var model = query.FirstOrDefault(m => m.ProductId == item.Id);
            if (model == null) continue;
            item.Count = model.Count;
        }
        return result;
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpOutstockProductDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ErpOutstockProductDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ErpOutstockProductDto model) =>
        await _thisRepository.InsertAsync(model.Adapt<ErpOutstockProduct>());

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ErpOutstockProductDto model) =>
        await _thisRepository.UpdateAsync(model.Adapt<ErpOutstockProduct>());

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
